// 在文件开头声明一个变量存储最新的分析结果
let lastAnalysisResult = null;

document.addEventListener('DOMContentLoaded', function() {
    const textInput = document.getElementById('textInput');
    const charCount = document.getElementById('charCount');
    const lineCount = document.getElementById('lineCount');

    // 实时更新字数和行数统计
    textInput.addEventListener('input', function() {
        updateTextStats(this.value);
    });

    function updateTextStats(text) {
        // 更新字数（去除空格和换行符）
        charCount.textContent = text.replace(/\s/g, '').length;
        // 更新行数
        lineCount.textContent = text.split('\n').length;
    }
});

async function analyzeText() {
    const textInput = document.getElementById('textInput');
    const textType = document.getElementById('textType');
    const resultArea = document.getElementById('analysisResult');
    const downloadBtn = document.getElementById('downloadBtn');
    
    if (!textInput.value.trim()) {
        alert('请输入需要分析的文字内容！');
        return;
    }

    // 显示加载状态
    resultArea.innerHTML = '正在分析中...';
    downloadBtn.style.display = 'none';
    
    try {
        // 调用后端API
        const response = await fetch('http://localhost:5000/api/analyze-text', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                content: textInput.value,
                serviceType: getServiceType(textType.value)
            })
        });

        if (!response.ok) {
            throw new Error('网络请求失败');
        }

        const data = await response.json();
        
        if (data.error) {
            throw new Error(data.error);
        }

        // 格式化显示检测结果
        if (data.code === 200 && data.data) {
            const result = data.data;
            const reason = JSON.parse(result.reason || '{}');
            
            // 获取标签的中文描述
            const labelMap = {
                'ad': '广告引流',
                'political_content': '涉政内容',
                'profanity': '辱骂内容',
                'contraband': '违禁内容',
                'sexual_content': '色情内容',
                'violence': '暴恐内容',
                'nonsense': '无意义内容',
                'negative_content': '不良内容',
                'religion': '宗教内容',
                'cyberbullying': '网络暴力',
                'ad_compliance': '广告法合规',
                'C_customized': '用户库命中'
            };

            // 风险等级配置
            const riskDetails = {
                high: {
                    text: '高风险',
                    color: '#ff4d4f',
                    icon: '⚠️',
                    description: '检测到严重风险内容，建议立即处理'
                },
                medium: {
                    text: '中风险',
                    color: '#fa8c16',
                    icon: '⚠️',
                    description: '检测到潜在风险内容，建议人工复核'
                },
                low: {
                    text: '低风险',
                    color: '#fadb14',
                    icon: 'ℹ️',
                    description: '检测到轻微风险内容，建议关注'
                },
                none: {
                    text: '无风险',
                    color: '#52c41a',
                    icon: '✅',
                    description: '未检测到风险内容'
                }
            };
            const riskLevel = (reason.riskLevel || 'none').toLowerCase();

            // 存储分析结果用于下载
            lastAnalysisResult = {
                检测时间: new Date().toLocaleString(),
                检测内容: textInput.value,
                检测类型: textType.value,
                分析结果: {
                    风险等级: riskDetails[riskLevel].text,
                    风险描述: result.descriptions,
                    检测标签: labelMap[result.labels] || result.labels,
                    风险提示: reason.riskTips,
                    命中风险词: reason.riskWords ? reason.riskWords.split(',') : []
                },
                原始响应: data.data
            };

            // 构建显示内容
            resultArea.innerHTML = `
                <div style="padding: 20px;">
                    <div style="
                        background: ${riskDetails[riskLevel].color}10;
                        border-left: 4px solid ${riskDetails[riskLevel].color};
                        padding: 16px;
                        margin-bottom: 20px;
                        border-radius: 4px;
                    ">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <span style="font-size: 1.5em; color: ${riskDetails[riskLevel].color}">
                                ${riskDetails[riskLevel].icon}
                            </span>
                            <div>
                                <h3 style="margin: 0; color: ${riskDetails[riskLevel].color}">
                                    ${riskDetails[riskLevel].text}
                                </h3>
                                <p style="margin: 8px 0 0; color: #666">
                                    ${result.descriptions || riskDetails[riskLevel].description}
                                </p>
                            </div>
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                        <div style="
                            padding: 15px;
                            background: #f8f9fa;
                            border-radius: 6px;
                        ">
                            <h4 style="color: #1890ff; margin: 0 0 10px 0;">🔖 检测标签</h4>
                            <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                                <span style="
                                    padding: 4px 12px;
                                    background: #e6f7ff;
                                    color: #1890ff;
                                    border-radius: 15px;
                                    font-size: 0.9em;
                                ">${labelMap[result.labels] || result.labels}</span>
                            </div>
                        </div>

                        <div style="
                            padding: 15px;
                            background: #f8f9fa;
                            border-radius: 6px;
                        ">
                            <h4 style="color: #1890ff; margin: 0 0 10px 0;">📌 风险提示</h4>
                            <div style="color: #666;">
                                ${reason.riskTips || '无'}
                            </div>
                        </div>

                        <div style="
                            padding: 15px;
                            background: #f8f9fa;
                            border-radius: 6px;
                            grid-column: 1 / -1;
                        ">
                            <h4 style="color: #1890ff; margin: 0 0 10px 0;">🔍 命中风险词</h4>
                            <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                                ${reason.riskWords ? 
                                    reason.riskWords.split(',').map(word => `
                                        <span style="
                                            padding: 4px 12px;
                                            background: #fff1f0;
                                            color: #ff4d4f;
                                            border-radius: 15px;
                                            font-size: 0.9em;
                                        ">${word.trim()}</span>
                                    `).join('') 
                                    : '<span style="color: #666;">无</span>'}
                            </div>
                        </div>
                    </div>

                    <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px;">
                        <details>
                            <summary style="color: #1890ff; cursor: pointer; font-size: 0.9em;">
                                📄 查看原始响应数据
                            </summary>
                            <pre style="
                                background: #f8f9fa;
                                padding: 15px;
                                border-radius: 4px;
                                margin-top: 10px;
                                overflow-x: auto;
                                font-size: 0.85em;
                            ">${JSON.stringify(data.data, null, 2)}</pre>
                        </details>
                    </div>
                </div>
            `;
            
            // 显示下载按钮
            downloadBtn.style.display = 'block';
        } else {
            resultArea.innerHTML = '<div style="text-align: center; padding: 20px;">未检测到风险</div>';
            downloadBtn.style.display = 'none';
        }
        
    } catch (error) {
        resultArea.innerHTML = `<div style="color: red; padding: 10px;">分析过程中出现错误：${error.message}</div>`;
        console.error('Error:', error);
        downloadBtn.style.display = 'none';
    }
}

// 获取服务类型
function getServiceType(selectedType) {
    const typeMap = {
        '教学内容检测': 'pgc_detection',
        '社交媒体检测': 'comment_detection',
        '私聊内容检测': 'chat_detection',
        'AI生成内容检测': 'ai_art_detection',
        '广告内容检测': 'ad_compliance_detection',
        '用户昵称检测': 'nickname_detection'
    };
    return typeMap[selectedType] || 'comment_detection';
}

// 下载结果功能
function downloadResult() {
    if (!lastAnalysisResult) {
        alert('没有可下载的分析结果');
        return;
    }

    // 创建Blob对象
    const blob = new Blob(
        [JSON.stringify(lastAnalysisResult, null, 2)], 
        { type: 'application/json;charset=utf-8' }
    );
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `文本分析结果_${new Date().toISOString().slice(0,19).replace(/[:-]/g, '')}.json`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 释放URL对象
    URL.revokeObjectURL(link.href);
} 